<?php
namespace App\Http\Controllers\Gateway\Page;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class RechargeController extends Controller
{
    public function pay(Request $request)
    {
        $mch_code = config('recharge.sandbox.mch_no');
        $app_id = config('recharge.sandbox.app_id');
        $key = config('recharge.sandbox.key');
        $data = $request->all();
        $data['mch_code'] = $mch_code;
        $data['app_id'] = $app_id;
        $data['key'] = $key;
        $signStr = '';
        $key = $data['key'];
        array_forget($data, 'key');
        ksort($data);
        foreach ($data as $k => $d) {
            $signStr .= $k . '=' . $d . '&';
        }
        $signStr .= $key;
        $sign = md5($signStr);
        $data['sign'] = $sign;

//        $url = route('gateway.recharge.pay') . '?' . http_build_query($data);
        $form = "<body onload='autoSubmit();'><form id='postForm' action='".route('gateway.recharge.pay')."' method='post'>";
        foreach ($data as $key => $value) {
            $form .= "<input type='hidden' value='{$value}' name='{$key}'>";
        }
        $form .= '</form></body><script type="text/javascript">function autoSubmit() { document.getElementById("postForm").submit()} </script>';
        return response($form);

    }

    public function callback(Request $request)
    {
        Log::info('异步通知:' . json_encode($request->all()));
        return response('success');
//        return json_encode($request->all());
    }
}
